var rowIndex = "%^%%%%";
var regid = 0;
var flag = true;
var value = 0;
var page;
var _id;
var startid;
var today;
var thisYear;
var thisMonth;

/**
 * @description: "创建委外结存"按钮点击事件
 */
$('#createSettleStorageBill').click(function() {
  showSwal(
    '创建',
    '您确定创建委外结存吗？',
    '是的，确定创建',
    function(result){
      if(result.value){
        // console.log(typeof $('#monthSelect').val());
        $.ajax({
          url: pathUrl("subcBal/createMonthSubcBal.action"),
          type: "POST",
          dataType: "JSON",
          data: {
            'year': $('#yearSelect').val(),
            'month': String(Number($('#monthSelect').val()) + 1),
          },
          success: function(data) {
            if (data.code == "0000") {
              swal_Tips_Short(data.message);
              $('#infoTable').bootstrapTable('refresh');
            } else if (data.code == "9999") {
              swal_Tips(data.message);
            }
          },
          error : function(request) {
            swal_Tips_Error();
          },
          complete: function () {
          },
        });
      }
    }
  );
});

/**
 * @description:设置默认列
 */
var resetColumn = [
  {
    field : 'fNumber',
    align : 'left',
    valign: 'middle',
  	// sortable : true,
    title : '物料代码',
    visible : true,
    width: '10%',
    // 是否是必选字段
    must:true,
    footerFormatter: function(value) {
        value = '合計';
        return value;
    },
  },
  {
    field : 'fName',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '物料名称',
    visible : true,
    width: '10%',
    must:true,
  },
  {
    field : 'fModel',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '规格型号',
    visible : true,
    width: '10%',
    must: true,
  },
  {
    field : 'tYear',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '年份',
    visible : true,
    width: '10%',
    must: true,
  },
  {
    field : 'tMonth',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '月份',
    visible : true,
    width: '10%',
    must: true,
  },
  {
    field : 'fSupplierName',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '供应商',
    visible : true,
    width: '10%',
    must: true,
  },
  {
    field : 'fOutQty',
    align : 'left',
    valign: 'middle',
    sortable : true,
    title : '转出数量',
    visible : true,
    width: '10%',
    must: true,
    footerFormatter: function(value) {
      var count = 0;
      for (var i in value) {
        if (value[i].fOutQty != null) {
            count += value[i].fOutQty;
        }
      }

      return count.toFixed();
    },
  },
  {
    field : 'fInQty',
    align : 'left',
    valign: 'middle',
    title : '转入数量',
    visible : true,
    width: '10%',
    must: true,
    footerFormatter: function(value) {
      var count = 0;
      for (var i in value) {
        if (value[i].fInQty != null) {
            count += value[i].fInQty;
        }
      }

      console.log(count);
      return count.toFixed();
    },
  },
  {
    field : 'fDate',
    align : 'left',
    valign: 'middle',
    title : '制单时间',
    visible : true,
    must: true,
    width: '10%',
    formatter: timeFormatter,
  },
];

var colArr = [];

/** 
 * @description: 预加载
 * @param : 
 */
$(function (){
  today = new Date();
  thisMonth = today.getMonth();
  thisYear = today.getFullYear();
  $('#monthSelect').val(thisMonth);
  for (let index = thisYear - 30; index < thisYear + 20; index++) {
    $('#yearSelect').append(`<option value="${index}">${index}</option>`);
  }
  $('#yearSelect').val(thisYear);
	initField();
	resizeIframeHight();
	loadRecordName("OSS", initTable);
	
	var time = {
		onClose : false,
		format : 'YYYY-MM-DD',
		donefun : function(obj) {
			// end.minDate = obj.val; // 开始日选好后，重置结束日的最小日期
			var attr = obj.elem.id;
			dataExport[attr] = obj.val;
		},
	};
});

/** 
 * @description: 初始化委外结存表
 * @param : 
 */
function initTable() {
	$("#infoTable").bootstrapTable('destroy').bootstrapTable({
    url: pathUrl("subcBal/findByCondition.action"),
    // 行高
		height: $(window).height() * 0.8,
		method: "POST",
		//striped : true,
    cache: false,
    // 分页方式：client客户端分页，server服务端分页（*）
		sidePagination: "server", 
		pagination: true,
		pageNumber: 1,
		pageSize: 10,
		pageList: [10, 30, 60, 100, 'ALL'],
		// colArr: colArr,
    showFooter: true,
    // 排序规则
		// sortOrder: 'desc', 
		exportDataType: "allServer",
		rowStyle: function(row, index) {
			var classes = [ 'success' ];
			if (index == rowIndex) {
				return { classes : classes[0] };
      }
      
			return {};
		},
		queryParams : function(params) {
			var data = {};
      // 排序列名
			var orderBy = (!params.sort) ? '' : (params.sort + " " + params.order);
			data.offset = params.offset + 1;
      data.row = params.limit;
      // 排序：要排序字段 + 排序规则
			data.orderBy = orderBy;
			console.log(sqlCombine);
      data.sqlStr = sqlCombine;
      console.log(sqlCombine);
			return data;
		},
		dataType: 'JSON',
		uniqueId: "id",
		columns: customColumn,
		onClickRow: function (row,$element) {
      // console.log(row)
      // 去除之前选中的行的，选中样式
      $('.success').removeClass('success');
      // 添加当前选中的 success样式用于区别
			$($element).addClass('success');
			index = $element.data('index');
			rowIndex = index;
			_index = index;
			page = $('.pagination .active').find("a").eq(0).text();
			_id = row.id
			
		},
		onPageChange : function(number, size) {
			if (page == number) {
				rowIndex = index;
			} else {
				$('.success').removeClass('success');
				rowIndex = "%^%%%%";
			}
		},
		onLoadSuccess:function(row){
			console.log(row);
		},
  });
}

/** 
 * @description: 查询按钮点击事件
 * @param :
 */
$("#oldquery").click(function() {
  reset();
});

/** 
 * @description: 重置按钮点击事件 
 * @param :
 */
$("#resetting").click(function(){
	$(".clean_C").val("");
	$('#tYear,#tMonth').selectpicker('refresh');
	for(prop in data){
		if(data.hasOwnProperty(prop)){
			data[prop] = '';
		}
	}
	reset();
});

/** 
 * @description: 重置
 * @param :
 */
function reset(){
	initTable();
	$('.success').removeClass('success');
	rowIndex = "%^%%%%";
}

/** 
 * @description: 查询条件按回车事件
 * @param :
 */
$("#fName, #fNumber, #fModel, #tYear, #tMonth, #fSupplierName, #fOutQty, #fInQty,#fDate").keypress(function(event) {
	if(event.keyCode === 13){
		initTable();
	}
});

// --------------------------------修改自js/TaiZhang/bgTzCommon.js-----------------------------------
/**
 * @description:拼接查询条件的字符串
 */
function executSql(){
	fDisPatchFlag = null;
	fStatus = null;
	fClosed = null;
	var field1 = $("#field1").val();
	var operator1 = $("#operator1").val();
  var value1 = $("#value1").val();
	
	if (
    field1 != "blank"
    && (field1 == ""
    || field1 == undefined
    || operator1 == ""
    || operator1 == undefined
    || value1 == ""
    || value1 == undefined)
  ) {
		swal_Tips("第一搜索组信息不完整，不能进行搜索");
		return false;
  }
  
	value1 = value1.trim();
	if (field1 !== 'blank') {
		sqlCombine = `(${field1} ${switchOper(operator1,value1)})`;
	}
	
	for(var i = 2 ;i <= searchCount; i++){
		var index = i - 1;
		var andOr = $("#andOr"+index).val();
		var field = $("#field"+i).val();
		var operator = $("#operator"+i).val();
		var value = $("#value"+i).val();

		if(field == "blank")
			continue;
		if (
			field != "blank"
			&& (field == ""
			|| field == undefined
			|| operator == ""
			|| operator == undefined
			|| value == ""
			|| value == undefined)
		) {
			swal_Tips("第"+i+"搜索组信息不完整，不能进行搜索");
			return false;
		}
		
		value = value.trim();
		if (sqlCombine === '') {
			sqlCombine += `(${field} ${switchOper(operator, value)})`;
		} else if (sqlCombine !== '') {
			sqlCombine += ` ${andOr} (${field} ${switchOper(operator, value)})`;
		}
	}

	console.log(sqlCombine);

	for(var l = 1 ;l <= searchCount; l++){
		$("#value"+l).unbind().bind("keyup", function(event) {
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		});
	}
}

/**
 * @description: 暂时不知怎么描述
 * @param {操作符} operator 
 * @param {值} value 
 */
function switchOper(operator,value){
  var statement;
  
	switch(operator){
	case 'like':
		statement = `like '%${value}%'`;
		break;
	case 'left like':
		statement = `like '${value}%'`;
		break;
	case 'right like':
		statement = "like "+"'%"+value+"'";
		statement = `like '%${value}'`;
		break;
	default:
		statement = operator+" '"+value+"'";
		statement = `${operator} '${value}'`;
  }
  
	return statement;
}

// ------------------------------js/TaiZhang/newtZCommon.js-----------------------------------------
var _fparentid = "-1",IDName = "";
var fNumber,fName,fModel;
var jj;
var _index;
var colField;
var customColumn = [];
var pageIds;
var searchCount = 1;
var sqlCombine = "";
var lastRecordName = "";
var initTableName;
var fDisPatchFlag = null;
var fStatus = null;
var fClosed = null;
var fOrderBillNo=null;

/*
 *@Description: 自定义列按钮点击事件
 * @param :
 */
$("#changeColumn").click(function(){
	createCustomColumn();
	$("#changeColumnModal").modal("show");
});

/*
 *@Description: 获取用户自定义的列
 * @param :
 */
function getColumn(pageId,funcName){	
	$.ajax({
		url : pathUrl("tz/getColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':pageId			
		},
		success : function(data) {
			if (data.code == "0000") {
				if(data.rows.length == 0){//初始化为默认列						
					customColumn = cloneObjectFn(resetColumn);
				}else{//自定义列					
					createTableClumn(data.rows[0].columns);					
				}				
				funcName();
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}

/**
 * @Description: 模态框显示
 * @param even
 * @returns
 */
function createTableClumn(col){
	var cols = new Array();
	cols = col.split(";");
	customColumn = cloneObjectFn(resetColumn);
	for(var i = 0; i < cols.length; i++){
		var temp = cols[i].split(",");
		var id = temp[1];
		for(var k = 0; k < customColumn.length; k++){
			if(customColumn[k].field != undefined && customColumn[k].field == id){
				if(temp[2] == "true"){
					customColumn[k].visible = true;	
				}else{
					customColumn[k].visible = false;
				}	
				customColumn[k].width = temp[3];
			}
		}
	}
}
/**
 * @Description: 实现点击div也可以实现checkbox的勾选或者取消
 * @param even
 * @returns
 */
function changeState(even){	
	var id = even.getAttribute("id").substr(0,even.getAttribute("id").length - 3);//获取id	
	var f = $("#" + id + "Check")[0].checked;
	if(f == true){
		$("#" + id + "Check")[0].checked = false;
	}else{
		$("#" + id + "Check")[0].checked = true;
	}
}

/*
 * @Description: 封装自定的列
 * @param : 
 */
function createCustomColumn(){		
	$("#cusColumn").html("");
	var h = "";
	colField = [];
	for(var i = 0,j = 0; i < customColumn.length; i++){
		var s = customColumn[i];
		if(s.field != undefined && s.field != ""){
			if(s.must == true){
				h += "<div class='customColumn'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left;' type='checkbox' checked = true ";
			}
			else if(s.hidden==true){
				h += "<div class='customColumn' style='display:none;'><div class='inputClass'><input class='inputCheck' disabled = true style='float: left; display:none;' type='checkbox' checked = true ";
			}
			else {
				h += "<div class='customColumn'><div class='inputClass'><input class='inputCheck' style='float: left;' type='checkbox' ";
				if(s.visible == true){
					h += "checked = true ";
				}
			}	
			var colTitle = formatTitle(s.title,"</br>");
			
			if(s.must == true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span>%<span></div><div style='float:right'>（必选）</div></div></div>";
			}
			else if(s.hidden==true){
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='float: left;'>"+colTitle+"</div>";
				h += "<div style='float:right;display:none;'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value='"+s.width.substr(0,s.width.length -1)+"'/>";
				h += "<span>%<span></div><div style='float:right;display:none;'>（必选）</div></div></div>";
			}
			else{
				h += "id = '"+s.field+"Check' value='"+colTitle+"'/><div style='width: 70%;float:left;' onclick='changeState(this)' id='" + s.field + "Div'>"+colTitle + "</div>";
				h += "<div style='float:right'><span>宽度</span><input style='inline-size: 39px;height: 17px;font-size: 15px;border: 0px;margin-left: 6px;' id='" + s.field +"Width' value = '" + s.width.substr(0,s.width.length -1) + "'/>";
				h += "<span>%<span></div></div></div>";
			}			
			colField[j] = s.field;
			j++;
		}
	}
	$("#cusColumn").html(h);	
}

/*
 * @Description: 保存自定义列
 * @param : 
 */
$("#confirmSave").click(function(){
	var datas = "";
	for(var i = 0; i < colField.length; i++){		
		var s = $("#" + colField[i] + "Check");
		var w = $("#" + colField[i] +"Width").val();		
		datas += s.val() + "," +colField[i] + "," +s[0].checked + ",";
		if(w == ""){
			w = 0;
		}
		datas += w + "%;"; 
	}
	datas = datas.substr(0,datas.length - 1);
	$.ajax({
		url : pathUrl("tz/saveColumn.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			'pageId':pageIds,
			'col' : datas
		},
		success : function(data) {
			$("#changeColumnModal").modal("hide");
			if (data.code == "0000") {
				swal_Tips_Short(data.message);
				getColumn(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
});

$("#resets").click(function(){
	var s = document.getElementsByClassName("inputCheck");
	for(var i = 0; i < s.length; i++){	
		s[i].checked = true;		
	}
	for(var i = 0; i < resetColumn.length; i++){
	 if(resetColumn[i].field != undefined){
		 var l = resetColumn[i].width;		 
		 $("#" + resetColumn[i].field + "Width").val(l.substr(0,l.length - 1));
	 }	
	}	
});

/**
 * 增加新的搜索组
 * @returns
 */
$("#addSearch").click(function(){
	if(searchCount >= 6){
		swal_Tips("搜索组数量已达上限");
		return;
	}
	var field = $("#field"+searchCount).val();
	var operator = $("#operator"+searchCount).val();
	var value = $("#value"+searchCount).val();
	if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
		swal_Tips("当前搜索组信息不完整，不能增加新的搜索组");
		return;
	}
	searchCount++;
	var searchId = "searchbox"+searchCount;
	$('#'+searchId).show();
});

/**
 * 初始化下拉框选项
 * @returns
 */
function initField(){
	for(var i = 0;i < resetColumn.length;i++){
		if(resetColumn[i].field != undefined && resetColumn[i].showSearch == undefined){
			$("#field1").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field2").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field3").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field4").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field5").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
			$("#field6").append("<option value='"+resetColumn[i].field+"'>"+resetColumn[i].title+"</option>");
		}
	}
	$('#searchbox2').hide();
	$('#searchbox3').hide();
	$('#searchbox4').hide();
	$('#searchbox5').hide();
	$('#searchbox6').hide();
}

/**
 * 进行自定义查询
 * @returns
 */
$("#query").click(function(){
	sqlCombine = "";
	var f = executSql();
	if(f == false){
		return;
	}else{
		initTableName();
	}
});

/**
 * 保存检索历史
 * @returns
 */
$("#saveSearch").click(function(){
	$("#saveModal").modal('show');	
});

/**
 * @description:
 */
$("#confirms").click(function(){
	if($("#recordName").val() == null || $("#recordName").val() == ""){
		swal_Tips("请输入检索名称");
		return;
	}
	var searchStr = "";
	var field1 = $("#field1").val();
	var operator1 = $("#operator1").val();
	var value1 = $("#value1").val();
	if(field1 != "blank" && (field1 == "" || field1 == undefined || operator1 == "" || operator1 == undefined || value1 == "" || value1 == undefined)){
		swal_Tips("第一搜索组信息不完整，不能进行保存");
		return false;
		
	}
	value1 = value1.trim();
	if(field1 != "blank"){
		searchStr += "field1,"+$("#field1").val()+",operator1,"+$("#operator1").val()+",value1,"+$("#value1").val()+";";
	}
	for(var i = 2;i <= searchCount;i++){
		var index = i-1;
		var andOr = $("#andOr"+index).val();
		var field = $("#field"+i).val();
		var operator = $("#operator"+i).val();
		var value = $("#value"+i).val();
		if($("#field"+i).val() == "blank")
			continue;
		if(searchStr == ""){
			if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
				swal_Tips("第"+i+"搜索组信息不完整，不能进行保存");
				return false;
			}
			value = value.trim();
			searchStr += "field"+i+
			","+$("#field"+i).val()+",operator"+i+","+$("#operator"+i).val()+",value"+i+","+$("#value"+i).val()+";";
		}
		else{
			if(field != "blank" && (field == "" || field == undefined || operator == "" || operator == undefined || value == "" || value == undefined)){
				swal_Tips("第"+i+"搜索组信息不完整，不能进行保存");
				return false;
			}
			value = value.trim();
			searchStr += "andOr"+index+","+$("#andOr"+index).val()+",field"+i+
			","+$("#field"+i).val()+",operator"+i+","+$("#operator"+i).val()+",value"+i+","+$("#value"+i).val()+";";
		}
		
	}
	var data = {
			pageId:pageIds,
			searchRecord:searchStr,
			recordName:$("#recordName").val()
	};
	$.ajax({
		url : pathUrl("tz/saveSearchRecord.action"),
		type : "POST",
		async:false,
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {
				swal_Tips_Short(data.message);
				$("#saveModal").modal('hide');
				loadRecordName(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
			
		}
	});
	$("#recordName").val("");	
	
});

/**
 * 重置搜索组状态
 * @returns
 */
$("#resetSearch").click(function(){
	sqlCombine = '';
	resetSearchGroup();
	initTableName();	
	$('#searchRecord').val('');
	$('#recordName').val('');
});

function resetSearchGroup(){
	fDisPatchFlag = null;
	fStatus = null;
	for(var index = 1; index <= 6 ;index++){
		$("#field"+index+" option:first").prop("selected", 'selected');
		$("#operator"+index+" option:first").prop("selected", 'selected');
		$("#value"+index).val("");
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		if(index < 6)
			$("#andOr"+index+" option:first").prop("selected", 'selected');
	}
	$('#searchbox2').hide();
	$('#searchbox3').hide();
	$('#searchbox4').hide();
	$('#searchbox5').hide();
	$('#searchbox6').hide();
	searchCount = 1;
}

/**
 * 根据检索历史的名字来加载历史检索记录
 * @returns
 */
function loadSearchRecord(){
	var recordName = $("#searchRecord").val();
	var data = {
			recordName:recordName,
			pageId:pageIds
	};
	if(recordName != "none")
		loadRecord(data);
}

function ifTime(index,fNumber,fName,fModel){
	$("#value"+index).val("");
	$("#valueBox"+index).html("");
	var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
	$("#valueBox"+index).html(h);
	$("#operator"+index).attr("disabled",false);
	var time = {
			onClose : false,
			format : 'YYYY-MM-DD',
			isTime:false,
			donefun : function(obj) {
			},
		};
	
	if (
		$('#field'+index).val() == "fDate"
		|| $('#field'+index).val() == "fStartDate" 
		|| $('#field'+index).val() == "fEndDate"
		|| $('#field'+index).val() == "fBillDate" 
		|| $('#field'+index).val() == "fCheckDate"
		|| $('#field'+index).val() == "fWorkDate" 
		|| $('#field'+index).val() == "fDownDate"
		|| $('#field'+index).val() == "fPlanCommitDate"
		|| $('#field'+index).val() == "fPlanFinishDate"
		|| $('#field'+index).val() == "fSchedulingCommitDate"
		|| $('#field'+index).val() == "fSchedulingFinishDate"
		|| $('#field'+index).val() == "fEndWorkDate"
		|| $('#field'+index).val() == "fArrivalDate"
	) {
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control-new searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		jeDate('#value'+index,time);
		$("#value"+index).unbind().bind("keyup",function (event) { 
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		})
	} else if ($('#field'+index).val() == "fSupplyName"){
			$("#valueBox"+index).html("");
			var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control searchInput' autocomplete='off'>";
			$("#valueBox"+index).html(h);
			console.log($("#valueBox"+index));
			$("#value"+index).typeahead({
					ajax: {
							url: pathUrl("supplier/getSupplierList.action"),
							timeout: 300,// 延时
							method: 'post',// 一定要小写
							triggerLength: 1,// 输入几个字符之后，开始请求
							loadingClass: null,// 加载数据时, 元素使用的样式类
							preDispatch: null,// 发出请求之前，调用的预处理方法
							preProcess: null// Ajax 请求完成之后，调用的后处理方法
					},
					display: "fName",     // 默认的对象属性名称为 name 属性
					val: "fItemID",           // 默认的标识属性名称为 id 属性
					items: '12'
			});
			$("#value"+index).bind("keyup",function (event) { 
				if (event.keyCode == 13) { 
					$('#query').triggerHandler('click'); 
				}
			});
		
	} else if($('#field'+index).val() == "fNumber" || $('#field'+index).val() == "fName" 
		|| $('#field'+index).val() == "fModel"){
		$("#value"+index).unbind().bind("keyup",function (event) {
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		});
	}
	else if($('#field'+index).val() == "fWorkType"){
		$("#operator"+index).find("option[value='=']").attr("selected",true); 
		//$("#operator"+index).attr("disabled",true);
		 $("#valueBox"+index).html("");
			
			var h = "<select name = 'value"+index + "' id = 'value"+index +"' class='form-control-new' data-live-search='true' data-width='85px'></select>";
			$("#valueBox"+index).html(h);
			$("#value"+index).append("<option title ='"+1+"'value='"+1+"'>"+"手动报工"+"</option>");
			$("#value"+index).append("<option title ='"+2+"'value='"+2+"'>"+"自动报工"+"</option>");
			$("#value"+index).append("<option title ='"+3+"'value='"+3+"'>"+"试车报工"+"</option>");
	}
	else{
		$("#valueBox"+index).html("");
		var h = "<input type='text' name='value"+index+"' id='value"+index+"' value='' class='form-control searchInput' autocomplete='off'>";
		$("#valueBox"+index).html(h);
		$("#value"+index).unbind().bind("keyup",function (event) { 
			if (event.keyCode == 13) { 
				$('#query').triggerHandler('click'); 
			}
		})
	}
}

/**
 * @description:
 * @param {*} data 
 */
function loadRecord(data){
	$('#recordName').val(data.recordName);
	$.ajax({
		url : pathUrl("tz/getSearchRecordByName.action"),
		type : "POST",
		async:false,
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {				
				resetSearchGroup();
                if(data.rows.length > 0){
                	var recordStr = data.rows.split(";");
    				for(var k = 1;k<=recordStr.length-1;k++){
    					$('#searchbox'+k).show();
    					searchCount++;
    				}
    				searchCount--;
    				for(var i=0;i<recordStr.length-1;i++){
    					if(i == 0){
    						var searchUnit = recordStr[i].split(",");
    						$("#field1").val(searchUnit[1]);
    						
    						$("#operator1").val(searchUnit[3]);
    						$("#value1").val(searchUnit[5]);
    						if(searchUnit[1] == "fWorkShop" || searchUnit[1] == "fDisPatchFlag" ||searchUnit[1] == "fDepName"
    							|| searchUnit[1] == "fStockName" ||searchUnit[1] == "fRwId" ||searchUnit[1] == "fStatus"
    								||searchUnit[1] == "fClosed"){
    							ifTime(1);
    							//$("#value1").val(searchUnit[5]);
    							$("#value1").find("option[value='"+searchUnit[5]+"']").attr("selected",true); 
    						}
    						
    					}
    					else{
    						var searchUnit = recordStr[i].split(",");
    						var index = i+1;
    						$("#andOr"+i).val(searchUnit[1]);
    						$("#field"+index).val(searchUnit[3]);
    						
    						$("#operator"+index).val(searchUnit[5]);
    						$("#value"+index).val(searchUnit[7]);
    						if(searchUnit[3] == "fWorkShop"|| searchUnit[3] == "fDisPatchFlag" ||searchUnit[3] == "fDepName"
    							|| searchUnit[3] == "fStockName" ||searchUnit[3] == "fRwId" ||searchUnit[3] == "fStatus"
    								||searchUnit[3] == "fClosed"){
    							ifTime(index);
    							//$("#value1").val(searchUnit[5]);
    							$("#value"+index).find("option[value='"+searchUnit[7]+"']").attr("selected",true); 
    						}
    					}
    				}
				}		
                else{
                	resetSearchGroup();
                	sqlCombine = "";
                }
				executSql();
				getColumn(pageIds,initTableName);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error("系统出错");
		}
	});
}

/**
 * 加载检索历史的名字
 * @returns
 */
function loadRecordName(pageId,initTables){
	pageIds = pageId;
	initTableName = initTables;
	$("#searchRecord").empty();
	$("#searchRecord").append("<option value='none'>"+"请选择"+"</option>");
	var data = {
			pageId:pageId
	};
	$.ajax({
		url : pathUrl("tz/getRecordName.action"),
		type : "POST",
		dataType : "JSON",
		data : data,
		success : function(data) {
			if (data.code == "0000") {					
				for(var i = 0;i<data.rows.length;i++){
					var s = data.rows[i];
					if(s.length > 5){
						s = data.rows[i].substr(0,5)+ "...";
					}
					$("#searchRecord").append("<option title ='"+data.rows[i]+"'value='"+data.rows[i]+"'>"+s+"</option>");
				}
				lastRecordName = data.rows[data.rows.length-1];
				$("#searchRecord").val(lastRecordName);
				var lastData = {
						recordName:lastRecordName,
						pageId:pageId
				};
				loadRecord(lastData);
			} else if (data.code == "9999") {
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}

function deleteRecord(){
	var recordName = $("#searchRecord").val();
	if(recordName == "none" || recordName == "" || recordName == null){
		swal_Tips("请选择一条检索历史进行删除");
		return;
	}
	var data = {
			pageId:pageIds,
			recordName:recordName
	}
	showSwal(
			'删除',
			'您确定删除吗？',
			'是的，确定删除',
			function(result){
				if(result.value){
					// console.log(_cardNo,_fOperNumber,_fQty,_fSupplierID,$("#price").val(),new
					// Date(_fFetchDate.replace(/-/g, "/")));
					showLoading("删除中...");//显示正在提交中
					$.ajax({
						url : pathUrl("tz/deleteSearchRecord.action"),
						type : "POST",
						dataType : "JSON",
						data : data,
						success : function(data) {
							if (data.code == "0000") {
								swal_Tips_Short(data.message);
								loadRecordName(pageIds,initTableName);
							} else if (data.code == "9999") {
								swal_Tips(data.message);
							}
						},
						error : function(request) {
							swal_Tips_Error();
						}
					});
				}
			});	
}
/**
 * 
 * @param title
 * @param f
 * @returns
 */
function formatTitle(title,f){
	var t = title.split(f);
	var titles = '';
	for(var i = 0; i < t.length; i++){
		titles += t[i];
	}
	return titles;
}